﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Quartz;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace H2O.Assistant.Jobs
{
    /// <summary>
    /// 钉钉作业
    /// 通过 webhook 调用自定义机器人发起喝水提醒
    /// </summary>
    [DisallowConcurrentExecution]
    public class DingTalkJob : IJob
    {
        private readonly ILogger _logger;
        private readonly IConfiguration _configuration;
        private readonly IHttpClientFactory _httpClientFactory;

        public DingTalkJob(ILogger<DingTalkJob> logger, IConfiguration configuration, IHttpClientFactory httpClientFactory)
        {
            _logger = logger;
            _configuration = configuration;
            _httpClientFactory = httpClientFactory;
        }

        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                string text = context.MergedJobDataMap.GetString(key: "text");
                string image = context.MergedJobDataMap.GetString(key: "image");
                //_logger.LogInformation(message: text);
                //_logger.LogInformation(message: image);

                bool enabled = _configuration.GetSection(key: "DingTalk").GetValue<bool>(key: "Enabled");
                _logger.LogInformation(message: $"DingTalk.Enabled = {enabled}");
                if (enabled == false)
                {
                    return Task.CompletedTask;
                }
                // 参考钉钉开发文档: https://open-doc.dingtalk.com/microapp/serverapi2/qf2nxq
                Uri webhook = _configuration.GetSection(key: "DingTalk").GetValue<Uri>(key: "WebHook");
                var message = new
                {
                    msgtype = "markdown",
                    markdown = new
                    {
                        title = text,
                        text = $@"
#### {text}
> ![]({image})"
                    }
                };

                HttpContent content = new StringContent(
                    content: JsonConvert.SerializeObject(message),
                    encoding: Encoding.UTF8,
                    mediaType: "application/json");
                HttpClient httpClient = _httpClientFactory.CreateClient(name: "dingtalk");
                //httpClient.DefaultRequestHeaders.Accept.Add(item: new MediaTypeWithQualityHeaderValue(mediaType: "application/json"));
                HttpResponseMessage httpResponseMessage = httpClient.PostAsync(requestUri: webhook, content: content).Result;
                _logger.LogInformation(message: $"{httpResponseMessage?.Content?.ReadAsStringAsync().Result}");
                return Task.CompletedTask;
            }
            catch (Exception ex)
            {
                throw new JobExecutionException(cause: ex);
            }
        }
    }
}
